import requests
from bs4 import BeautifulSoup
import logging

# 没有继续完整的编写，定义的类不太科学的。

'''
singer = input("请输入歌手名：")

url = f'https://music.91q.com/search?word={singer}'

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
}

# DataFrame = [
#     {
#     'musicname': '',
#     'musicid': '',
#     'singer': ''
#     },
#     {
#     'musicname': '',
#     'musicid': '',
#     'singer': ''
#     }
# ]

DataFrame = {
    'musicname_list': [],
    'musicid_list': [],
    'singer_list': []
}

response = requests.get(url, headers=headers)

# print(response.text)
soup = BeautifulSoup(response.text, 'html.parser')
song_box = soup.find_all(name='div', class_='song-box')
for i in song_box:
    DataFrame['musicname_list'].append(i.find('a').text)
    DataFrame['musicid_list'].append(i.find('a').get('href'))

singer_box = soup.find_all(name='div', class_='artist ellipsis')
# print(singer_box)

# for i in singer_box:
#     i = i.find_all(name='a')
#     DataFrame['singer_list'].append([a.get_text(strip=True) for a in i])

for i in singer_box:
    i = i.find_all(name='a')
    DataFrame['singer_list'].append(
        ", ".join(a.get_text(strip=True) for a in i))
print(DataFrame)
'''

logging.basicConfig(
    level=logging.WARNING,  # 设置日志级别为 INFO（会输出 ERROR 及以上级别）
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[logging.StreamHandler()]  # 输出到控制台
)

# 想定义一个类，存储查询到的所有音乐信息


class media_source():
    def __init__(self, musicname, musicid, singer):
        self.musicname = musicname
        self.musicid = musicid
        self.singer = singer

    def __repr__(self) -> str:
        return f'MediaSource(musicname={self.musicname}, musicid={self.musicid}, singer={self.singer})'


# 定义用来获取音乐信息的函数
def fetch_music_info(singer):
    # singer = input("请输入歌手名：")
    url = f'https://music.91q.com/search?word={singer}'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
    }

    try:
        response = requests.get(url, headers=headers)
        if response.history != []:   # history 会记录重定向过程的信息
            logging.info(f'Sites redirected: {response.history}')
        if response.status_code != 200:
            logging.error(
                f'Requests Error: {response.status_code}, {response.reason}')
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        logging.error(f"Error in fetching music info: {e}")
        return []

    soup = BeautifulSoup(response.text, 'html.parser')
    song_box = soup.find_all(name='div', class_='song-box')
    singer_box = soup.find_all(name='div', class_='artist ellipsis')

    music_info = []
    for song, singer_list in zip(song_box, singer_box):
        musicname = song.find('a').text
        musicid = song.find('a').get('href')
        i = singer_list.find_all(name='a')
        singer = ", ".join(a.get_text(strip=True) for a in i)
        music_info.append({'musicname': musicname, 'musicid': musicid, 'singer': singer})

    return music_info
